from django.db import models
from django.contrib.auth.models import User
from django.core.exceptions import SuspiciousOperation
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class ReputationDimension(models.Model):
    name = models.CharField(max_length=70)
    created_dt = models.DateTimeField(auto_now_add=True)
    modified_dt = models.DateTimeField(auto_now=True)
    

class ReputationScore(models.Model):

    user = models.ForeignKey(User)
    score = models.IntegerField()

    # dimension and aggregation are None if the ReputationScore itself is an aggregation
    dimension = models.ForeignKey(ReputationDimension, null=True)
    aggregation = models.ForeignKey('self', null=True)

    created_dt = models.DateTimeField(auto_now_add=True)
    modified_dt = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = ("user", "dimension")


class ReputationEvent(models.Model):
    
    user = models.ForeignKey(User)
    initiator = models.ForeignKey(User, related_name="initiated_event_set")  

    score = models.ForeignKey(ReputationScore)
    score_delta = models.IntegerField()
    aggregation = models.ForeignKey(ReputationScore, related_name="aggregated_event_set")
    aggregation_delta = models.IntegerField()

    dimension = models.CharField(max_length=70, null=True, blank=True)
    related_object = generic.GenericForeignKey('content_type', 'object_id')

    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()

    created_dt = models.DateTimeField(auto_now_add=True)

    def save(self):
        if not self.id:
            super(ReputationEvent, self).save()
        raise SuspiciousOperation("A ReputationEvent cannot be modified after it is created.")

